package com.ideal.gpt.app.local;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.lzwork.utility.collection.MapReader;
import com.lzwork.utility.file.FileUtility;
import com.lzwork.utility.file.LineContent;
import com.lzwork.utility.logger.LOGGER;
import com.lzwork.utility.officeparser.ExcelReader;
import com.lzwork.utility.officeparser.ExcelReader.Line;
import com.lzwork.utility.officeparser.ExcelReader.Page;
import com.lzwork.utility.officeparser.ExcelReader.XlsData;
import com.lzwork.web.RemoteCaller;
import com.lzwork.web.RemoteCaller.CallResult;

/**
 * @author LiZheng
 * @date 2024年1月5日 15:55:09
 */

public class WordToVector
{
	public WordToVector(String server)
	{
		this.url = server;
	}

	String url;

	RemoteCaller caller = new RemoteCaller();

	public List<?> getVector(String content)
	{
		JSONObject param = new JSONObject();
		param.put("content", content);

		CallResult result = caller.post(url, param, null);

		JSONObject obj = result.getReturnData();

		List<?> vec = MapReader.getMapArray(obj, "vector");
		return vec;
	}

	public float getVecCosSim(String first, String second)
	{
		JSONObject param = new JSONObject();
		param.put("first", first);
		param.put("second", second);

		CallResult result = caller.post(url, param, null);

		JSONObject obj = result.getReturnData();
		double sim = MapReader.getMapDouble(obj, "sim", -1, false);
		return (float) sim;
	}

	public void parseExcel(File input, String idKey, String contentKey)
	{
		XlsData pages = ExcelReader.read(input);

		String prefix = input.getParent();
		if (prefix == null)
			prefix = "./";
		else
			prefix += "/";
		prefix += FileUtility.getFileName(input);

		for (Page page : pages)
		{
			File output = new File(prefix + "_" + page.getName() + ".jsonl");
			List<String> toWrite = new ArrayList<>();

			LOGGER.log(LOGGER.PARSE, "Parsing page " + page.getName() + " with " + page.getLines().size() + " lines.");

			for (Line line : page.getLines())
			{
				String key = line.getFieldData(idKey);
				String content = line.getFieldData(contentKey);

				List<?> vec = getVector(content);

				JSONObject obj = new JSONObject(true);
				obj.put("id", key);
				obj.put("vec", vec);
				toWrite.add(obj.toJSONString());
			}

			LineContent.saveFile(output, toWrite);
		}
	}

	public static void main(String[] args)
	{
		String url = "http://172.31.106.163:7666/bgeembed";

		String idKey = "工单编号";
		String contentKey = "事件提取";

		File input = new File("V:/12345/similar_orders/gd_20240103_update_2200.xlsx");

		WordToVector parser = new WordToVector(url);
		parser.parseExcel(input, idKey, contentKey);
	}

}
